<!-- @format -->

<template>
  <base-search
    placeholder="请输入讲者姓名、手机号搜索"
    @search="handleCustomSearch"
  ></base-search>
  <div class="list pl-3 pr-3">
    <van-empty
      v-if="list.length == 0"
      image="//projectimg-1256680128.cos.ap-beijing.myqcloud.com/lpm/bd4d50fd-1214-423a-bbe8-2bc72dbd45b3.png"
      image-size="80"
      description="您尚未添加讲者，请先添加讲者"
    />

    <van-list
      v-model:loading="loading"
      :finished="total <= list.length"
      finished-text="没有更多讲者了"
      @load="loadMore"
    >
      <div
        v-for="(item, index) in list"
        :key="item.id"
        :class="index ? 'mt-3' : ''"
      >
        <base-card>
          <template #title>
            <div
              class="title_info"
              @click.stop="avatarClickHandler(item.id)"
            >
              <img
                class="avatar__inner"
                v-if="item.avatar"
                :src="`//${item.avatar}`"
                alt=""
              />
              <img
                class="avatar__inner"
                v-else
                src="http://projectimg-1256680128.cos.ap-beijing.myqcloud.com/lpm/d74df4cb-358e-4b87-8652-36e08fd2f584.png"
                alt=""
              />
              <span>{{ item.name }}</span>
              <van-uploader
                :after-read="uploadAvatarAfterRead"
                @click-upload="clickUploadAvatar(item, index)"
              >
                <van-tag type="primary" class="ml-2">上传头像</van-tag>
              </van-uploader>
            </div>
          </template>
          <div class="card-container">
            <van-cell title="医院">{{ item.hospital || '--' }}</van-cell>
            <van-cell title="科室">{{ item.department || '--' }}</van-cell>
            <van-cell title="职称">{{ item.title || '--' }}</van-cell>
            <van-cell title="注册时间">{{ item.gmtCreate }}</van-cell>
            <van-cell title="状态">
              <van-tag
                :type="getAuditStatusType(item.status)"
                size="small"
                plain
              >
                {{ getAuditStatus(item.status) }}
              </van-tag>
            </van-cell>
            <van-cell
              v-if="item.status === 3"
              title="拒绝原因"
            >
              <span class="text-danger">{{ item.reason }}</span>
            </van-cell>
          </div>
          <!-- !item.isScan &&  -->
          <view
            class="text-center"
            v-if="![3, 4].includes(item.status)"
          >
            <div
              @click.stop="clickSpeakerDetail(item.id)"
              class="pt-3 text-primary"
            >
              <span>查看详情</span>
            </div>
          </view>
          <!-- && !item.isScan -->
          <div
            class="action_bar van-hairline--top"
            v-if="[3, 4].includes(item.status)"
          >
            <div
              class="text-danger van-hairline--right"
              @click.stop="clickSpeakerDelete(item.id)"
            >
              <span>删除</span>
            </div>
            <div>
              <span
                class="text-primary"
                @click="clickSpeakerUpdate(item.id)"
                >完善信息</span
              >
            </div>
          </div>
        </base-card>
      </div>
    </van-list>
    <van-action-sheet
      v-model:show="showAvatarAction"
      :actions="avatarActions"
      cancel-text="取消"
      close-on-click-action
      @cancel="showAvatarAction = false"
    />

    <van-back-top
      right="5vw"
      bottom="17vh"
      style="z-index: 101"
    />
  </div>
  <AddSpeaker ref="refAddSpeaker" />
</template>

<script setup>
import AddSpeaker from './components/add-speaker.vue'
import { ref, inject, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import useList from '@/hooks/useList'
import useUtils from '@/hooks/useUtils'
import { showConfirmDialog, showSuccessToast, showToast } from 'vant'

const api = inject('api')
const router = useRouter()
const refAddSpeaker = ref()
const showAvatarAction = ref(false)
const avatarSelected = ref(0)
const avatarActions = reactive([
  { name: '预览照片', index: 1 },
  { name: '更换照片', index: 1 },
])

const {
  loading,
  search,
  list,
  total,
  loadMore,
  handleClearSearch,
  handleSearch,
} = useList({
  queryApi: api.speakerList,
  search: {
    key: '',
  },
})

const avatarClickHandler = (id) => {
  // avatarSelected.value = id
  // showAvatarAction.value = true
}

const handleCustomSearch = (val) => {
  search.key = val
  handleSearch()
}

// 点击讲者详情
const clickSpeakerDetail = (id) =>
  router.push(`/vol/detail-speaker/${id}?type=detail`)
//完善讲者信息
const clickSpeakerUpdate = (id) =>
  router.push(`/vol/detail-speaker/${id}?type=update`)
//删除暂存的讲者
const clickSpeakerDelete = (id) => {
  showConfirmDialog({
    title: '提示',
    message: '确认删除这该讲者么？',
  })
    .then(() => {
      api.speakerDel(id).then((res) => {
        if (res.code === 0) {
          showSuccessToast('删除成功')
          handleClearSearch()
        }
      })
    })
    .catch(() => {})
}
// 获取审核状态
const getAuditStatus = (val) => useUtils().speakerAuditStatus(val)
const getAuditStatusType = (val) => useUtils().speakerAuditStatusType(val)

// 上传头像逻辑开始
const uploadAvatar = reactive({
  speaker: null,
  index: 0,
  loading: false
});
function clickUploadAvatar (speaker, index) {
  if (uploadAvatar.loading) {
    showToast(`${uploadAvatar.speaker.name}讲者上传头像中，请稍等`)
    return;
  }
  uploadAvatar.speaker = speaker;
  uploadAvatar.index = index;
}
function uploadAvatarAfterRead (file) {
  const formData = new FormData();
  formData.append("file", file.file);
  api.portraitV2Avatar(formData).then(res => {
    if (!res.code) {
      api.uploadSpeakerAvatar({
        avatar: res.data,
        speakerId: uploadAvatar.speaker.id
      }).then(result => {
        uploadAvatar.loading = false;
        if (!result.code) {
          showToast('头像上传成功')
          list.value[uploadAvatar.index].avatar = res.data
        }
      }).catch(() => {
        uploadAvatar.loading = false;
      })
    } else {
      uploadAvatar.loading = false;
    }
  }).catch(() => {
    uploadAvatar.loading = false;
  })
}
// 上传头像逻辑结束
onMounted(() => {
  handleClearSearch()
  console.log(list.value)
})
</script>

<style scoped lang="less">
.title_info {
  display: flex;
  align-items: center;
  .avatar__inner {
    width: 30px;
    height: 30px;
    border-radius: 50%;
    vertical-align: middle;
    margin-right: 10px;
  }
}
.action_bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 50px;
  > div {
    flex: 1;
    box-sizing: border-box;
    text-align: center;
    line-height: 50px;
  }
}
</style>
